<template>
  <view class="my-remark">
		<view v-if="hasLogin" class="remark-background">
			<view class="cover-color">
				<view class="label-box">
					<label>美食名称：</label>
					<input v-model="foodName" class="input" type="text" placeholder-class="ipnut-placeholder"
					:focus="true" placeholder="今天吃了什么呢？" @input="getFoodTips" @blur="judgeNewFood" />
				</view>
				<view v-if="foodTips.length !== 0" class="food-tips">
					<text>你吃的是不是：</text>
					<view class="example-body">
						<view v-for="(item,index) in foodTips" class="tag-view" :key="index">
							<uni-tag  :text="item.name"  @click="tagsClick(index)"/>
						</view>
					</view>
				</view>
				<view class="label-box">
					<label>店铺地址：</label>
					<input v-model="address" class="input" type="text" placeholder-class="ipnut-placeholder"
							placeholder="我们可以在哪里吃到这个好吃的东西呢？" 
							@input="inputAddress" @blur="judgeNewFood"/>
				</view>
				
				<textarea v-model="comments"  class="textarea"  placeholder="今天的饭吃得开心吗？给大家分享一下你的感受吧~"  placeholder-class="ipnut-placeholder"/>
				<textarea v-model="description"  class="textarea"  v-if="isNewFood" placeholder-class="ipnut-placeholder"
					placeholder="哇~你发现了一个新美食呢,简单描述一下它是什么吧~ " />
					
				<view class="uni-uploader">
					<view class="uni-uploader-body">
						<view class="uni-uploader-head">
							<view >上传的第一张图片会作为封面哦~</view>
							<view class="uni-uploader-info">{{imgLen}}/9</view>
						</view>
						<view class="uni-uploader__files">
							<block v-for="(image,index) in imageList" :key="index">
								<view class="uni-uploader__file">
									<image mode="scaleToFill" :src="image" :data-src="image"></image>
									<uni-icons type="clear" @click="deleteImg(index)" class="cross-icon"></uni-icons>
									<!-- <uni-badge class="cross-icon" text="x" @click="deleteImg(index)"></uni-badge> -->
								</view>
							</block>
							<view class="uni-uploader__input-box" v-if="imgLen < 9">
								<view class="uni-uploader__input" @tap="chooseImage"></view>
							</view>
						</view>
					</view>
				</view>
				<view class="rate">
					<text>总体感受</text>
					<uni-rate class="uni-rate" v-model="rateValue" activeColor="#fa541c" 
								allow-half :size="25" :margin="18" color="rgba(0,0,0,0.5)"/>
				</view>
				<view class="pick-wrap">
					<picker  name="gender" @change="changeSource" :range="['本校', '外校']" :value="[source]">
						<view class="school-list">
							<text class="title">美食来源</text>
							<view class="footer">
								<view class="uni-list-item__extra">
									<text>{{source === 0 ? '本校': '外校'}}</text>
								</view>
								<uni-icons :size="16" class="uni-icon-wrapper" color="#bbb" type="arrowright" />
							</view>
						</view>
					</picker>
					<picker
						v-if="source == 1"
						mode="multiSelector" @columnchange="schoolColumnChange"
						:value="multiIndex" :range="multiArray" range-key="name" @change="changeSchool"
					>
						<view class="school-list school">
							<text class="title">学校</text>
							<view class="footer">
								<view class="uni-list-item__extra">
									<text>{{multiArray[2][multiIndex[2]].name}}</text>
								</view>
								<uni-icons :size="16" class="uni-icon-wrapper" color="#bbb" type="arrowright" />
							</view>
						</view>
						<!-- <input :disabled="true" v-model="multiArray[2][multiIndex[2]].name" class="schoolInput"  placeholder="点击选择学校" /> -->
					</picker>
				</view>
				<button @click="submit">发表点评</button>
			</view>
		</view>
		<view v-else>
			<goto-login></goto-login>
		</view>
  </view>
</template>

<script>
import {
	uniForms, uniFormsItem, uniRate, uniIcons, uniSearchBar, 
	uniBadge, uniTag} from '@dcloudio/uni-ui'
import permision from "@/common/js/permission.js"
import {getSchoolTree} from '@/api/user.js'
import {getFoodByFilter} from '@/api/food.js'
import {addByFoodContent, addByFoodId} from '@/api/remark.js'
import {mapState, mapActions} from 'vuex'
import gotoLogin from '../share/gotoLogin.vue'
export default {
  name: 'create-remark',
  components: {
    uniForms, uniFormsItem, uniRate, uniIcons, uniSearchBar, uniBadge, uniTag,
    gotoLogin
  },
  data() {
  	return {
		foodName: '',
		address: '',
		source: 0,
  		imageList: [],
  		countIndex: 8,
		isNewFood: false,
		foodId: null,
  		count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
		foodTips: [],
		comments: '',
		rateValue: 0,
		multiIndex: [-1, -1, -1],
		multiArray: [[], [], []],
  	}
  },
  computed:{
	imgLen() {return this.imageList.length},
	...mapState(['hasLogin', 'userInfo', 'baseTarget', 'schoolData']),
  },
  methods: {
	...mapActions(['setSchoolData']),
	inputAddress(){
		this.foodId = ''
	},
	judgeNewFood(){ // 绑定输入框的移除焦点
		this.foodTips = []
		if(this.foodId || !this.foodName){
			this.isNewFood = false
		}else{
			this.isNewFood = true
		}
	},
	getFoodTips(){  // 绑定输入框的input操作
		this.foodId = ''
		let schoolId = this.userInfo.schoolId
		if(this.source === 1){ // 所选学校的foodId
			if(this.multiIndex[2] < 0){  // 还没有选学校
				schoolId = undefined;
			}else{
				schoolId = this.multiArray[2][this.multiIndex[2]].schoolId
			}
		}
		getFoodByFilter({foodName: this.foodName, schoolId}).then(res=>{
			if(res.code === 200){
				this.foodTips = res.data
			}
		}).catch(err=>console.log(err))
	},
	tagsClick(index){
		this.foodName = this.foodTips[index].name
		this.address = this.foodTips[index].address
		this.foodId = this.foodTips[index].id
		this.foodTips = []
	},
	getSchoolData(){
		this.setSchoolData().then(data=>{
			this.multiArray = [
				data, data[0].cityVOList, data[0].cityVOList[0].schoolList,
			]
		})
	},
	changeSchool(e){
		console.log('change', e)
		this.multiIndex = e.detail.value
	},
	schoolColumnChange(e){
		const {column, value} = e.detail
		this.multiIndex[column] = value
		switch(column){
			case 0:  // 选择的是第一列
				this.multiArray[1] = this.multiArray[0][value].cityVOList
				this.multiArray[2] = this.multiArray[1][0].schoolList
				this.multiIndex[1] = 0
				this.multiIndex[2] = 0
				break;
			case 1:  // 选择的是第二列
				this.multiArray[2] = this.multiArray[1][value].schoolList
				this.multiIndex[2] = 0
				break;
			default: break;
		}
		this.$forceUpdate()
	},
	changeSource(e){
		console.log(e.detail)
		this.source = e.detail.value
		if(e.detail.value==1 && this.multiArray[0].length === 0){
			this.getSchoolData()
		}
	},
	// 提交表单
	submit(e) {  // 发表评论
		let {schoolId, id: userId} = this.userInfo
		const {description, comments, rateValue: score, foodName, address, foodId } = this
		if(!foodName) {uni.showToast({title: '我们都想知道你今天吃了什么呢~', icon: 'none'}); return;}
		if(!address) {uni.showToast({title: '告诉我们这个好吃的东西是在哪里吧~', icon: 'none'});return;}
		if(!comments) {uni.showToast({title: '我们都想知道你今天吃饭开不开心呢~', icon: 'none'});return;}
		if(score === 0){
			uni.showToast({title: '对这顿饭的整体感受进行评分吧~', icon: 'none'}); return;
		}
		if(this.source == 1){  // 外校美食
			if(this.multiIndex[2] < 0){
				uni.showToast({ title:"非本校美食要选择学校哦~", icon: 'none'}); return;
			}
			schoolId = this.multiArray[2][this.multiIndex[2]].schoolId
		}
		let formData
		if(foodId){
			formData = {foodId, userId,  score, comments, schoolId}
		}else{
			formData = {foodName, address, userId, description, score, comments, schoolId}
		}
		console.log(formData)
		if(this.imageList.length === 0){  // 用户没有上传图片
			this.createRemarkNoPhoto(formData)
		}else{
			this.createRemark(formData)
		}
	},
	gotoFoodGround(){ // 去往美食星球
		uni.switchTab(
			{
				url: '/pages/share/index',
				success: function (e) { 
					const page = getCurrentPages().pop(); 
					if (page == undefined || page == null) return; 
					page.onLoad(); 
				} 
			}
		)  
	},
	createRemarkNoPhoto(formData){
		const req = formData.foodId ? addByFoodId(formData) : addByFoodContent(formData)
		req.then(res=>{
			uni.showToast({title: '发表点评成功！'})
			this.clearData()
			this.gotoFoodGround()
		}).catch(err=>{uni.showToast({title:'我们的网络出现了一点错误，请稍候再试~', icon: 'none'})})
	},
	createRemark(formData){
		const url = formData.foodId ? '/comment/addByFoodId' : '/comment/addByFoodContent'
		uni.showLoading({
		  title: '正在努力上传中...',
		  mask: true
		});
		let that = this
		uni.uploadFile({
			url: this.baseTarget + url,
			filePath: this.imageList[0],
			name: 'photo',
			formData: formData,
			success: res =>{
				if(res.data.code === 200){
					if(that.imageList.length === 1){
						uni.showToast({title: '发表点评成功！'})
						that.clearData()
						this.gotoFoodGround()
					}else{  // 上传评论的其他图片
						const commentId = res.data.data
						let imageUploadList = [];
						for(let i = 1; i < that.imageList.length; i ++){
							console.log('图片列表', that.imageList[i])
							imageUploadList.push(that.uploadCommentPhoto(that.imageList[i], commentId))
						}
						Promise.all(imageUploadList).then(res=>{
							uni.showToast({title: '发表点评成功！'})
							that.clearData()
							that.gotoFoodGround()
						}).catch(err=>{   // 其他图片上传有失败的情况
							uni.showToast({title: '发表点评成功,但部分图片上传失败', icon: 'none'})
							that.gotoFoodGround()
						})
					}
				}else{
					uni.showToast({title: res.data.message, icon: 'none'})
				}
			},
			fail: res=>{uni.showToast({title:'我们的网络出现了一点错误，请稍候再试~', icon: 'none'})},
			complete: () => {uni.hideLoading()}
		})
	},
	uploadCommentPhoto(photo, commentId){
		let that = this
		return new Promise((resolve, reject)=>{
			console.log('上传其他图片', that.baseTarget)
			uni.uploadFile({
				url: that.baseTarget + `/comment/insertPhoto/${commentId}`,  // 上传图片的url
				filePath: photo,
				name: 'photo',
				success: (res)=>{
					if(res.data.code === 200){
						console.log('上传图片',res)
						resolve(res)
					}
					else{ reject(res) }
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	clearData(){
		this.foodName= ''
		this. address = ''
		this.source = 0
		this. imageList = []
		this.isNewFood = false
		this.foodId = null
		this.foodTips = []
		this.comments = ''
		this.rateValue = 0
	},
	error(e) {
		console.log(e.detail);
	},
	deleteImg(index){
		this.imageList.splice(index, 1)
	},
	chooseImage: async function() {
		if (this.imageList.length === 9) {
			let isContinue = await this.isFullImg();
			console.log("是否继续?", isContinue);
			if (!isContinue) {
				return;
			}
		}
		uni.chooseImage({
			sourceType: ['camera', 'album'],
			sizeType: ['compressed', 'original'],
			count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
			success: (res) => {
				for(let i = 0; i < res.tempFiles.length; i++){
					if(res.tempFiles[i].size > 2097152){
						uni.showToast({title: '上传的图片大小不能大于2M，请重新选择图片上传~', icon: 'none'})
						continue;
					}
					this.imageList.push(res.tempFilePaths[i])
				}
				// this.imageList = this.imageList.concat(res.tempFilePaths);
			},
			fail: (err) => {
				// #ifdef MP
				// uni.getSetting({
				// 	success: (res) => {
				// 		let authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
				// 		if (!authStatus) {
				// 			uni.showModal({
				// 				title: '授权失败',
				// 				content: '校园美食点评需要从您的相机或相册获取图片，请在设置界面打开相关权限',
				// 				success: (res) => {
				// 					if (res.confirm) {
				// 						uni.openSetting()
				// 					}
				// 				}
				// 			})
				// 		}
				// 	}
				// })
				// #endif
			}
		})
	},
	isFullImg: function() {
		return new Promise((res) => {
			uni.showModal({
				content: "已经有9张图片了,是否清空现有图片？",
				success: (e) => {
					if (e.confirm) {
						this.imageList = [];
						res(true);
					} else {
						res(false)
					}
				},
				fail: () => {
					res(false)
				}
			})
		})
	},
  }
}
</script>

<style lang='scss'>

/* 头条、百度小程序组件内不能引入字体 */
	/* #ifdef MP-BAIDU */
	@font-face {
		font-family: uniicons;
		font-weight: normal;
		font-style: normal;
		src: url("~@/static/uni.ttf") format("truetype");
	}
	/* #endif */
	page{
		
	}
 
 .my-remark{
	font-size: 30rpx;
	.remark-background{
		background: url("~@/static/remarkBackground.jpg") no-repeat;
		/* background-color: #FFFFFF; */
		background-attachment:fixed;
		margin:0px;
		background-size:100% 100%;
		min-height: 100vh;
		.cover-color{
			padding: 10rpx;
			background-color: rgba(255, 255, 255, 0.8);
			min-height: 100vh;
		}
	}
	.food-tips{
		padding: 0 25rpx;
		color: #999;
		font-size: 24rpx;
		.example-body {
			display: flex;
			flex-direction: row;
			justify-content: flex-start;
			flex-wrap: wrap;
			padding: 0 20rpx;
			.tag-view {
				/* #ifndef APP-PLUS-NVUE */
				display: flex;
				/* #endif */
				flex-direction: column;
				margin: 10rpx 5rpx;
				justify-content: center;
			}
		}
	}
	.label-box{
		display: flex;
		margin: 10rpx 0;
		label{
			line-height: 60rpx;
		}
		.input {
			height: 60rpx;
			padding: 15rpx 25rpx;
			line-height: 50rpx;
			font-size: 28rpx;
			background: rgba(255, 242, 232, 0.6);
			flex: 1;
			border-radius: 5px;
		}
	}
	
	.pick-wrap{
		margin-top: 20rpx;
		padding: 0 25rpx;
		border-bottom: #999 solid 0.5px;
		border-top: #999 solid 0.5px;
		
		.school-list{
			display: flex;
			justify-content: space-between;
			font-size: 16px;
			position: relative;
			padding: 25rpx 0rpx 25rpx 30rpx;
			.footer{
				display: flex;
			}
			.title{
				font-size: 14px;
				color: #3b4144;
				overflow: hidden;
			}
			.uni-list-item__extra {
				/* #ifndef APP-NVUE */
				display: flex;
				/* #endif */
				flex-direction: row;
				justify-content: flex-end;
				align-items: center;
				color: #999;
				font-size: 12px;
			}
		}
		.school{
			border-top: #e5e5e5 solid 0.5px;
		}
	}
	
	.rate{
		display: flex;
		padding: 0 25rpx;
		align-items: center;
		justify-content: center;
		.uni-rate{
			padding: 15rpx 25rpx;
		}
	}
	
	.ipnut-placeholder{
		color: #999;
		line-height: 50rpx;
	}
	
	.schoolInput{
		width: 550rpx;
		height: 60rpx;
		padding: 15rpx 25rpx;
		line-height: 50rpx;
		font-size: 28rpx;
		background: #FFF;
		flex: 1;
	}
	.textarea {
		margin-top: 5px;
		padding: 15rpx 25rpx;
		font-size: 28rpx;
		background: rgba(255, 242, 232, 0.6);
		height: 150rpx;
		line-height: 50rpx;
		width: 93%;
		border-radius: 5px;
	}
 }

 button {
    margin-top: 30rpx;
    background-color: $theme-color;
    color: #ffffff;
    &::after{
      border: none;
    }
  }
  
 
  .uni-uploader {
  	flex: 1;
  	flex-direction: column;
	padding: 10rpx 25rpx;
  }
  .uni-uploader-head {
  	display: flex;
  	flex-direction: row;
  	justify-content: space-between;
	color: #666;
	font-size: 24rpx;
  }
  .uni-uploader-info {
  	color: #999;
  }
  /* .uni-uploader-body {
  	margin-top: 16rpx;
  } */
  .uni-uploader__files {
  	display: flex;
  	flex-direction: row;
  	flex-wrap: wrap;
  }
  .uni-uploader__file {
	position: relative;
  	margin: 0 10rpx 0 10rpx;
  	width: 200rpx;
  	height: 200rpx;
	image{
		width: 200rpx;
		height: 200rpx;
		position: relative;
	}
	.cross-icon{
		position: absolute;
		width: 20rpx;
		height: 20rpx;
		left: 185rpx;
		top: -10rpx;
	}
  }
  
  /* .uni-uploader__img {
  	display: block;
	position: relative;
  	width: 180rpx;
  	height: 180rpx;
  } */
  .uni-uploader__input-box {
  	position: relative;
  	margin:10rpx;
  	width: 175rpx;
  	height: 175rpx;
	background-color: rgba(255,255,255, 0.7);
  	/* border: 2rpx solid #D9D9D9; */
  }
  .uni-uploader__input-box:before,
  .uni-uploader__input-box:after {
  	content: " ";
  	position: absolute;
  	top: 50%;
  	left: 50%;
  	-webkit-transform: translate(-50%, -50%);
  	transform: translate(-50%, -50%);
  	background-color: #D9D9D9;
  }
  .uni-uploader__input-box:before {
  	width: 4rpx;
  	height: 79rpx;
  }
  .uni-uploader__input-box:after {
  	width: 79rpx;
  	height: 4rpx;
  }

  .uni-uploader__input {
  	position: absolute;
  	z-index: 1;
  	top: 0;
  	left: 0;
  	width: 100%;
  	height: 100%;
  	opacity: 0;
  }
  
</style>


